package com.kinon.tyjaccount.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.kinon.tyjaccount.Constatus;
import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.adapter.DingdanAdapter;
import com.kinon.tyjaccount.adapter.UrgentDingdanAdapter;
import com.kinon.tyjaccount.entity.DingdanEntity;
import com.kinon.tyjaccount.sqlitebean.SettletmentBean;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.SysTimeManage;
import com.kinon.tyjaccount.tools.ToastUtil;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;

/**
 * @author：郑谦
 * @时间：2017-3-16 下午5:38:13
 * @类名：DingdanFragment.java
 * @功能: 订单记录
 */
public class DingdanFragment extends Fragment{

	private PullToRefreshListView pull_dingdan;
	/**没有商品*/
	private TextView tv_none;
	private int offset = 0;
	private int page = 10;
	HttpTools toolModel=null;
	String token;
	/** 商品信息的集合 */
	private ArrayList<DingdanEntity> dingdanslist;
	DingdanAdapter dingdanAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_dingdan, null);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initRes();
	}
	private void initRes() {
		SharedPreferences sp = getActivity().getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		pull_dingdan = (PullToRefreshListView) getView().findViewById(
				R.id.pull_dingdan);

		pull_dingdan.setMode(Mode.BOTH);
		pull_dingdan.setOnRefreshListener(onrefresh);
		//		pull_twosort.setOnItemClickListener(itemclicke);
		tv_none = (TextView)getView().findViewById(R.id.tv_none);

		//判断是否是紧急情况
		if(!Constatus.URGENT_TYPE){
			pull_dingdan.setMode(Mode.BOTH);
			pull_dingdan.setOnRefreshListener(onrefresh);
			getDingdaninfo();
		}else{
			getSettletment();
		}

	}

	/**紧急情况下运行的代码*/
	private void getSettletment(){
		long sysTime=System.currentTimeMillis();
		String date= SysTimeManage.getInstage().getDate(sysTime);
		ArrayList<SettletmentBean> mDestList =
				(ArrayList<SettletmentBean>) DataSupport.where("date=?",date)
						.order("orderno desc")
						.find(SettletmentBean.class);
		UrgentDingdanAdapter adapter=new UrgentDingdanAdapter(getActivity(),mDestList);
		pull_dingdan.setAdapter(adapter);
	}

	/**获取订单记录*/
	private void getDingdaninfo() {
		if(NetWorkUtil.isNetwork(getActivity())==false)
		{
			ToastUtil toastUtil=new ToastUtil();
			toastUtil.Short(getActivity(),"  "+"当前网络不可用")
					.setToastBackground(Color.WHITE,0).show();
//			Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
			return;
		}
		dingdanslist = new ArrayList<DingdanEntity>();

		toolModel = new HttpTools(getActivity());
		toolModel.getOrders(token, page + "", offset + "","1",
				new JsonDingdan());
	}

	private class JsonDingdan extends JsonHttpResponseHandler {

		@Override
		public void onSuccess(int statusCode, Header[] headers,
							  JSONObject response) {
			super.onSuccess(statusCode, headers, response);

			try {
				Log.i("info","订单列表----"+response.toString());
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if (code==true) {
					JSONObject data = response.getJSONObject("data");
					int unprintnum=data.getInt("unprintnum");
					JSONArray orders=data.getJSONArray("orders");
					for (int i = 0; i < orders.length(); i++) {
						JSONObject object = orders.getJSONObject(i);
						String id=object.getString("id");
						String name=object.getString("name");
						String orderno=object.getString("orderno");
						String total=object.getString("total");
						String order_time=object.getString("order_time");
						String refund=object.getString("refund");
						dingdanslist.add(new DingdanEntity(id, orderno, name, total, order_time,refund));
					}
//					Log.e("info","-----3");
					if (dingdanslist.size()==0) {
						tv_none.setVisibility(View.VISIBLE);
					}else {
						tv_none.setVisibility(View.GONE);
					}
					dingdanAdapter=new DingdanAdapter(getActivity(), dingdanslist);
					pull_dingdan.setAdapter(dingdanAdapter);
					pull_dingdan.getRefreshableView().setSelection(offset);
					pull_dingdan.setDividerDrawable(null);
					//				Utility.setGridViewHeightBasedOnChildren(pull_twosort);
					pull_dingdan.onRefreshComplete();
				}else {
					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
				}


			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(Throwable e, JSONObject errorResponse) {
			super.onFailure(e, errorResponse);
			Toast.makeText(getActivity(),
					"网络请求失败", Toast.LENGTH_SHORT).show();
		}

	}


	/** 上下拉刷新 */
	private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {

		@Override
		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
			offset = 0;
			dingdanslist.clear();
			toolModel.getOrders(token, page + "", offset + "", "1",
					new JsonDingdan());
			if(NetWorkUtil.isNetwork(getActivity())==false)
			{
				//				MyToast.mytoast(getActivity(), "当前网络不可用");
				Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
				pull_dingdan.onRefreshComplete();
				return;
			}

		}

		@Override
		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
			offset += page;
			toolModel.getOrders(token, page + "", offset + "", "1",
					new JsonDingdan());
			//			setSection();
			//			adapter.notifyDataSetChanged();
			if(NetWorkUtil.isNetwork(getActivity())==false)
			{
				Toast.makeText(getActivity(), "当前网络不可用", Toast.LENGTH_SHORT).show();
				pull_dingdan.onRefreshComplete();
				return;
			}
		}

	};

}
